package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.FindPasswordDto;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.FindPwdService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class FindPwdServiceImpl implements FindPwdService {

    @Autowired
    private CheckCodeClient checkCodeClient;

    @Autowired
    private XcUserMapper xcUserMapper;

    /**
     * 找回密码
     *
     * @param findPasswordDto 找回密码表单数据
     * @return 是否成功
     */
    @Override
    public Boolean findpassword(FindPasswordDto findPasswordDto) {
        // 判断两次密码是否一致
        String password = findPasswordDto.getPassword();
        String confirmPwd = findPasswordDto.getConfirmpwd();
        if (StringUtils.isBlank(password) || StringUtils.isBlank(confirmPwd))
            throw new RuntimeException("密码不能为空");
        if (!Objects.equals(password, confirmPwd)) throw new RuntimeException("两次输入的密码不一致");

        // 判断验证码是否正确
        String checkCode = findPasswordDto.getCheckcode();
        if (StringUtils.isBlank(checkCode)) throw new RuntimeException("验证码为空");
        String key = findPasswordDto.getCheckcodekey();
        Boolean verified = checkCodeClient.verify(key, checkCode);
        if (!verified) throw new RuntimeException("验证码错误");

        // 根据邮箱号查询该用户是否存在
        String email = findPasswordDto.getEmail();
        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XcUser::getEmail, email);
        XcUser user = xcUserMapper.selectOne(queryWrapper);
        if (user == null) throw new RuntimeException("用户不存在");

        // 用户存在，修改密码
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        int updated = xcUserMapper.updateById(user);
        if (updated != 1) throw new RuntimeException("修改密码失败");
        // 修改成功
        return true;
    }
}
